import cv2
import numpy as np
from matplotlib import pyplot as plt

def show_photo(name,picture):#图像显示函数
    cv2.imshow(name,picture)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

img1 = cv2.imread('pic4.jpg',0)
img2 = cv2.imread('pic5.png',0)

show_photo('img1',img1)
show_photo('img2',img2)

sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None)#kp1为关键点，des1为对应的特征向量
kp2, des2 = sift.detectAndCompute(img2,None)
bf = cv2.BFMatcher(crossCheck = True)

#1对1的匹配
matches = bf.match(des1,des2)
matches = sorted(matches, key = lambda x:x.distance)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=2)
show_photo('img3',img3)

#k对最佳匹配
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2,k=2)

good = []
for m,n in matches:
    if m.distance <0.75 * n.distance:
        good.append([m])

img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)
show_photo('img3',img3)
